const express = require('express')
const appServer = express()

// 解决获取不到请求体问题
appServer.use(express.json());
appServer.use(express.urlencoded({extended: false}))

// 解决 H5端 的跨域问题
appServer.use("*", function(req, res, next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,content-type,*");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    next();
})


/**
 * 优化 res.send() 代码， 进行全局注册一个中间件， 为 res 对象挂载一个 res.cc() 函数
 */
appServer.use((req, res, next) => {
    // status = 200 为成功; status = 404 为失败﹔默认将status 的值设置为1，方便处理失败的情况
    res.ErrorFun = function(err, status = 500){
        res.send({
            // 状态
            status,
            // 状态描述， 判断 err 时 错误对象 还是 字符串
            message: err instanceof Error ? err.message : err
        })
    }
    next()
})

const expressJWT = require('express-jwt')
const config = require('./JWT_Config')
appServer.use(expressJWT({algorithms:[ "HS256" ], secret: config.secretKey }).unless({ path: [/^\/api\//] }))


// 捕获解析 JWT 失败后产生的错误
appServer.use((err, req, res, next) => {
    // Token 解析失败导致的错误
    if(err.name === "UnauthorizedError"){
        return res.send({status: 403, message: '身份认证失败！'})
    }
    res.send({status: 500, message: '未知错误！'})
})


// 部署本地静态图片文件
appServer.use('/api/classifiedListImgs', express.static('./classifiedListImgs'))
appServer.use('/api/usedGoodsImgs', express.static('./usedGoodsImgs'))
appServer.use('/api/headImages', express.static('./headImages'))
appServer.use('/api/confessionWallImgs', express.static('./confessionWallImgs'))


// 部署 H5 端项目
appServer.use('/api/SecondarySchoolOnCampus', express.static('./h5'))


// 引入并使用路由
const getPublic_router = require('./router/getPublic_router')
const notificationInformation_router = require('./router/notificationInformation_router')
const sendMail_router = require('./router/sendMail_router')
const user_router = require('./router/user_router')
const upload_imgRouter = require('./router/upload_imgRouter')
const usedGoods_router  = require('./router/usedGoods_router')
const confessionWall_router = require('./router/confessionWall_router')
appServer.use('/api', getPublic_router)
appServer.use('/api', notificationInformation_router)
appServer.use('/api', sendMail_router)
appServer.use(upload_imgRouter)
appServer.use(user_router)
appServer.use(usedGoods_router)
appServer.use(confessionWall_router)



appServer.listen(4080, () => {
    console.log('本地IP：http://localhost:4080')
})  